//
//  NewUserViewController.m
//  MyVirtualDiary
//
//  Created by Alexander Wallis on 09.07.13.
//  Copyright (c) 2013 Alexander Wallis. All rights reserved.
//

#import "NewUserViewController.h"
#import "AppDelegate.h"
#import "User.h"


@interface NewUserViewController ()

@end

@implementation NewUserViewController
@synthesize nameField = _nameField;
@synthesize passwordField = _passwordField;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (IBAction)add:(id)sender {
}

-(IBAction)backgroundTouched:(id)sender{

    [_nameField resignFirstResponder];
    [_passwordField resignFirstResponder];
    
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{

    if (textField == _nameField || textField == _passwordField) {
        [_nameField resignFirstResponder];
        [_passwordField resignFirstResponder];
    }
    return NO;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    /*
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addUser)];
    self.navigationItem.rightBarButtonItem = item; 
    */
    //self.navigationController.navigationBar.topItem.title = @"New User";
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Private Methods 

-(AppDelegate *)appDelegate{

    return (AppDelegate *)[[UIApplication sharedApplication]delegate];
    
}

-(IBAction)cancel:(id)sender{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(IBAction)save:(id)sender{
    //check if user and password is empty
    if([[self.nameField text]length] == 0 || [[self.passwordField text]length] == 0){
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Error" message:@"Fill in User and Password" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }else{
    NSManagedObjectContext *context = [[self appDelegate]managedObjectContext];
    
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"User" inManagedObjectContext:context];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name==%@", self.nameField.text];
    
    [fetchRequest setEntity:entity];
    [fetchRequest setPredicate:predicate];
    
    NSError *error = nil; 
    NSArray *array = [context executeFetchRequest:fetchRequest error:&error];
    
    if (array.lastObject != NULL) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"User already exists" message:@"select another Username" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show]; 
    }else{
        
        User* user = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:context];
        user.name = self.nameField.text;
        user.password = self.passwordField.text;
        
        if ([context save:&error]) {
            NSLog(@"User: %@ - Password: %@ added", self.nameField.text, self.passwordField.text);
        }else{
            NSLog(@"the save wasn't successful %@", [error userInfo]);
        }
      [self dismissViewControllerAnimated:YES completion:nil];
        
    }
    }
}
@end
